//
//  BDAddrAddTableTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/3.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDAddrAddTableTableViewController.h"

@interface BDAddrAddTableTableViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *addrTextField;
@property (weak, nonatomic) IBOutlet UITextField *detailAddrTextField;
@property (weak, nonatomic) IBOutlet UITextField *postTextField;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

@end

@implementation BDAddrAddTableTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"Add Address", nil);
    
    UITapGestureRecognizer *tap =
    [[UITapGestureRecognizer alloc]  initWithTarget:self action:@selector(dismissMyKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    _saveButton.layer.cornerRadius = 5.0;
    _saveButton.layer.masksToBounds = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_userAddr != nil) {
        if (![_userAddr[@"receiver"] isEqual:[NSNull null]]) {
            _nameTextField.text = _userAddr[@"receiver"];
        }
        if (![_userAddr[@"telephone"] isEqual:[NSNull null]]) {
            _phoneTextField.text = _userAddr[@"telephone"];
        }
        if (![_userAddr[@"region"] isEqual:[NSNull null]]) {
            _addrTextField.text = _userAddr[@"region"];
        }
        if (![_userAddr[@"detailAddress"] isEqual:[NSNull null]]) {
            _detailAddrTextField.text = _userAddr[@"detailAddress"];
        }
        if (![_userAddr[@"postcode"] isEqual:[NSNull null]]) {
            _postTextField.text = _userAddr[@"postcode"];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - TextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    
    if ([_nameTextField.text length]
        && [_phoneTextField.text length]
        && [_addrTextField.text length]
        && [_detailAddrTextField.text length]) {
        _saveButton.enabled = YES;
    } else {
        _saveButton.enabled = NO;
    }
    
    if (textField == _phoneTextField) {
        if (futrueString.length > kUserNameLength) {// 包括手机号码和邮箱
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 101) {
        [_phoneTextField becomeFirstResponder];
    } else if (textField.tag == 102) {
        [_addrTextField becomeFirstResponder];
    } else if (textField.tag == 103) {
        [_detailAddrTextField becomeFirstResponder];
    } else if (textField.tag == 104) {
        [_postTextField becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
        [self saveAddrButtonPressed:nil];
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //  解决键盘挡住tableView问题
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= kScreen_Width - 216) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
        [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // 恢复键盘多出的高度
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)dismissMyKeyboard {
    [self.view endEditing:YES];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark IBActions

- (IBAction)saveAddrButtonPressed:(UIButton *)sender {
    if (_nameTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Receiver name is blank", nil)];
    } else if (_nameTextField.text.length > 56) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Receiver name over 56 characters", nil)];
    }  else if (_phoneTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"phone/email is blank", nil)];
    }  else if (!([_phoneTextField.text isValidPhoneNum] ||
                  [_phoneTextField.text isVaildEmail] ||
                  [_phoneTextField.text isValidDianHuaNum])) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"phone/email format is invalid", nil)];
    } else if (_addrTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Province、City、District is  blank", nil)];
    } else if (_addrTextField.text.length > 126) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Province、City、District over 126 characters", nil)];
    } else if (_detailAddrTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"detail address is blank", nil)];
    } else if (_detailAddrTextField.text.length > 126) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"detail address over 126 characters", nil)];
    } else {
        sender.enabled = NO;
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,Addr_Add];
        NSDictionary *parameters;
        NSString *method;
        if (![_userAddr[@"id"] isEqual:[NSNull null]] && [_userAddr valueForKey:@"id"]) {
            NSInteger addrId = [_userAddr[@"id"] integerValue];
            parameters = @{@"userId":[BDAccountManagerModel shareInstance].userId,
                           @"receiver":_nameTextField.text,
                           @"telephone":_phoneTextField.text,
                           @"region":_addrTextField.text,
                           @"detailAddress":_detailAddrTextField.text,
                           @"postcode":_postTextField.text,
                           @"id":@(addrId)};
            method = @"PUT";
        } else {
            parameters = @{@"userId":[BDAccountManagerModel shareInstance].userId,
                           @"receiver":_nameTextField.text,
                           @"telephone":_phoneTextField.text,
                           @"region":_addrTextField.text,
                           @"detailAddress":_detailAddrTextField.text,
                           @"postcode":_postTextField.text};
            method = @"POST";
        }
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"saving", nil)];
        
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:method parameters:parameters completionHandler:^(NSObject *results, NSError *error) {
            sender.enabled = YES;
            if (error != nil) {
                NSLog(@"保存地址失败:%@",error);
                hud.labelText = NSLocalizedString(@"save address failed", nil);
                [hud hideAfterDelay:0.5];
            } else {
                NSLog(@"result = %@",results);
                hud.labelText = NSLocalizedString(@"save address success", nil);
                [hud hideAfterDelay:0.5];
                
                [[BDAccountManagerModel shareInstance] setLogin:YES];
                
                dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
                dispatch_after(time, dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            }
        }];
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
